package com.shangcheng.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shangcheng.commons.utils.JwtUtils;
import com.shangcheng.dubbo.api.*;
import com.shangcheng.model.domain.*;
import com.shangcheng.model.vo.AdminVo;
import com.shangcheng.model.vo.PageResult;
import com.shangcheng.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import java.util.*;

@Service
public class UmsAdminService {

    @DubboReference
    private AdminApi adminApi;

    @DubboReference
    private UmsMenuApi menuApi;

    @DubboReference
    private AdminRoleRelationApi adminRoleRelationApi;

    @DubboReference
    private UmsRoleApi umsroleApi;


    //验证登录
    public Map login(String username, String password) {
        //查询用户是否存在
        Admin admin = adminApi.selectOne(username);
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        if (admin == null || !pwd.equals(admin.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        if (admin.getStatus() == 0) {
            throw new BusinessException("该用户已被禁用");
        }
        //生成token
        Map tokenMap = new HashMap<>();
        tokenMap.put("id", admin.getId());
        tokenMap.put("username", admin.getUsername());
        String token = JwtUtils.getToken(tokenMap);
        //返回token
        Map retMap = new HashMap<>();
        retMap.put("tokenHead", "Bearer");
        retMap.put("token", token);


        return retMap;
    }


    //注册
    public Admin register(Admin admin) {
        //获取当前用户名
        Admin ad = adminApi.selectOne(admin.getUsername());
        if (ad != null) {
            throw new RuntimeException("该用户已存在");
        }
        //如果不存在,将信息存入到新用户
        Admin admin1 = new Admin();
        admin1.setUsername(admin.getUsername());
        admin1.setPassword(SecureUtil.md5(admin.getPassword()));
        admin1.setNickName(admin.getNickName());
        admin1.setEmail(admin.getEmail());
        admin1.setIcon(admin.getIcon());
        admin1.setNote(admin.getNote());
        admin1.setCreateTime(new Date());
        admin1.setLoginTime(new Date());
        admin1.setStatus(1);
        //保存用户信息
        Admin newAdmin = adminApi.register(admin1);
        return newAdmin;
    }

    //删除指定用户信息
    public int deleteById(Integer id) {
        int row = adminApi.deleteById(id);
        return row;
    }

    //获取登录者的用户信息
    public AdminVo findUser(String username) {
        //查询用户信息
        Admin admin = adminApi.selectOne(username);
        //通过admin获取获取角色id
        List<AdminRoleRelation> relationList = adminRoleRelationApi.getRole(Convert.toInt(admin.getId()));
        //根据roleId获取角色菜单
        List<UmsMenu> menus=new ArrayList<>();
        for (AdminRoleRelation role : relationList) {
            List<UmsRoleMenuRelation> menuIdByRole = umsroleApi.findMenuIdByRole(Convert.toInt(role.getRoleId()));
            List<Integer> menuIds = CollUtil.getFieldValues(menuIdByRole, "menuId", Integer.class);
            for (Integer menuId : menuIds) {
                UmsMenu menu = menuApi.findById(menuId);
                menus.add(menu);
            }
        }
        //构建返回对象
        AdminVo adminVo = new AdminVo();
        String icon = admin.getIcon();
        String roles = admin.getNickName();
        adminVo.setIcon(icon);
        List<String> roleList = new ArrayList<>();
        roleList.add(roles);
        adminVo.setRoles(roleList);
        adminVo.setMenus(menus);
        adminVo.setUsername(username);
        return adminVo;
    }

    public PageResult list(Integer pageNum, Integer pageSize, String keyword) {
        //查询用户列表
        Page<Admin> pageInfo = adminApi.selectPage(pageNum, pageSize, keyword);
        List<Admin> adminList = pageInfo.getRecords();

        //构建返回对象
        PageResult pageResult = new PageResult(pageNum, pageSize, adminList.size(), adminList);
        return pageResult;
    }

    //获取指定用户的角色
    public List<UmsRole> getRole(Integer adminId) {
        //查询中间表中所有关于该用户的角色
        List<AdminRoleRelation> list = adminRoleRelationApi.getRole(adminId);
        if (ObjectUtils.isEmpty(list)){
            return null;
        }
        //取出所有的角色信息(role)的id
        List<Long> roleIds = CollUtil.getFieldValues(list, "roleId", Long.class);
        //根据roleIds查询所有的角色信息
        List<UmsRole> roles = umsroleApi.selectByIds(roleIds);
        return roles;
    }

    //给用户分配角色
    public int update(Integer adminId, List<Integer> roleIds) {
        List<AdminRoleRelation> role = adminRoleRelationApi.getRole(adminId);
        //将roleIds转换成List<Long>
        List<Long> roleIdsLong = CollUtil.newArrayList();
        for (Integer id : roleIds) {
            roleIdsLong.add(Long.valueOf(id));
        }
        //查询出该用户所有的角色
        //List<Role> roles = roleApi.selectByIds(roleIdsLong);
        //删除中间表中的所有关于该用户的角色
        adminRoleRelationApi.removeById(adminId);
        //插入中间表
        adminRoleRelationApi.insert(adminId, roleIdsLong);
        return roleIds.size();
    }

    //获取指定用户信息
    public Admin getMsg(Integer id) {
        Admin admin = adminApi.selectById(id);
        return admin;
    }

    //修改指定用户的信息
    public int updateById(Integer id, Admin admin) {
        if (ObjectUtils.isEmpty(admin)){
            deleteById(id);
        }
        String password = admin.getPassword();
        password = SecureUtil.md5(password);
        admin.setId(Long.valueOf(id));
        admin.setPassword(password);
        int row =  adminApi.updateById(admin);
        return row;
    }



    //修改指定用户密码
    public int updatepwd(Map map) {
        String username = (String) map.get("username");
        String oldPassword = (String) map.get("oldPassword");
        String newPassword = (String) map.get("newPassword");
        //查询用户是否存在
        Admin admin = adminApi.selectOne(username);
        if(ObjectUtils.isEmpty(admin)){
            throw new RuntimeException("用户不存在");
        }
        //判断新密码是否为空
        if(ObjectUtils.isEmpty(newPassword)){
            throw new RuntimeException("新密码不能为空");
        }
        //判断新旧密码是否一致
        if(newPassword.equals(oldPassword)){
            throw new RuntimeException("新旧密码不能一致");
        }
        admin.setPassword(SecureUtil.md5(newPassword));
        int row = adminApi.updateById(admin);
        return row;
    }

    //修改指定用户状态
    public int updateStatus(Integer id, Integer status) {
        //根据id查询用户信息
        Admin admin = adminApi.selectById(id);
        admin.setStatus(status);
        int row = adminApi.updateById(admin);
        return row;
    }
}
